package com.myrslok.set;

import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ResourceSet<R> {

    private Set<ResourceSupplier<R>> resourceSuppliers = new HashSet<ResourceSupplier<R>>();

    public ResourceSet() {
    }

    public boolean add(@NotNull final ResourceSupplier<R> rs) {
        return this.resourceSuppliers.add(rs);
    }

    public boolean add(@NotNull final R... r) {
        final ResourceSupplier<R> supplier = new ResourceSupplier<R>() {
            @Override
            public Set<R> getResources() {
                final Set<R> set = new HashSet<R>();
                set.addAll(Arrays.asList(r));
                return set;
            }
        };
        return resourceSuppliers.add(supplier);
    }

    public Set<R> getResources() {
        final HashSet<R> set = new HashSet<R>();
        for (final ResourceSupplier<R> r : resourceSuppliers) {
            set.addAll(r.getResources());
        }
        return set;
    }

    public ResourceAction<R> run(@NotNull final ResourceAction<R> action) {
        for (final ResourceSupplier<R> rs : resourceSuppliers) {
            for (final R t : rs.getResources()) {
                action.run(t);
            }
        }
        return action;
    }

    public interface ResourceAction<T> {
        void run(T r);
    }

    public interface ResourceSupplier<T> {
        public Set<T> getResources();
    }

}
